package Internet;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Test2 {
    //UDP数据报
    public static void main(String[] args) {
        UdpServer udpServer = new UdpServer();
        UdpClient udpClient = new UdpClient();
        udpClient.start();
        udpServer.start();
    }

}
class UdpServer extends Thread{//发送数据报
    @Override
    public void run() {
        /*DatagramPacket类的构造方法(byte[] data,int length,InetAddress address,int port)
        将数组data的length长度的元素发送到ip地址为address的port端口 */
        while (true){
            try {
            Thread.sleep(300);
            System.out.println("发送消息");
            Scanner scanner = new Scanner(System.in);
            String string = scanner.nextLine();
            byte[] bytes=string.getBytes();
                InetAddress byName = InetAddress.getByName("192.168.1.117");
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, byName, 9090);//打包数据
                DatagramSocket datagramSocket = new DatagramSocket();//发送数据
                datagramSocket.send(datagramPacket);
                datagramSocket.close();
            }catch (IOException |InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
class UdpClient extends Thread{//接受数据报
    @Override
    public void run() {
        while (true){
            try {
                byte[] bytes = new byte[100];
                DatagramPacket datagramPacket = new DatagramPacket(bytes, 22);
                DatagramSocket datagramSocket = new DatagramSocket(9090);
                datagramSocket.receive(datagramPacket);
                datagramSocket.close();
                System.out.print("收到的消息");
                System.out.println(new String(bytes));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}